#include "ObjectPool.hpp"
#include <vector>
#include <ctime>

struct TreeNode
{
    int _val;
    TreeNode* _left;
    TreeNode* _right;

    TreeNode():_val(0), _left(nullptr), _right(nullptr)
    {}
};

void TestObjectPool()//将malloc和定长内存池进行对比
{
    const int rounds = 10;//申请释放的轮次

    const size_t n = 100000;//每次申请释放多少次

    std::vector<TreeNode*> v1;
    v1.reserve(n);
    //测试malloc
    size_t begin1 = clock();
    for(int i = 0; i < rounds; i++)
    {
        for(int j = 0; j < n; j++)
        {
            v1.push_back(new TreeNode);//new底层就是用了malloc
        }
        for(int j = 0; j < n; j++)
        {
            delete v1[j];//delete底层就是用了free
        }
        v1.clear();
    }
    size_t end1 = clock();

    std::vector<TreeNode*> v2;
    v2.reserve(n);
    
    //创建一个定长内存池
    ObjectPool<TreeNode> tn_pool;

    size_t begin2 = clock();
    for(int i = 0; i < rounds; i++)
    {
        for(int j = 0; j < n; j++)
        {
            v2.push_back(tn_pool.New());
        }
        for(int j = 0; j < n; j++)
        {
            tn_pool.Delete(v2[j]);
        }
        v2.clear();
    }
    size_t end2 = clock();

    cout << "malloc cost: " << end1-begin1 << "ms" << endl;
    cout << "objpool cost: " << end2-begin2 << "ms" << endl;
}

int main()
{
    // TestObjectPool();

    return 0;
}